<route lang="yaml">
  meta:
    title: 权限管理
    requiresAuth: true
    permissions: ['sys:perm:manage']
</route>

<script setup lang="ts">
import { ElMessage } from 'element-plus'
import { ref } from 'vue'

interface Permission {
  id: string
  label: string
  children?: Permission[]
  isMenu?: boolean
  parentId?: string
}

// interface RolePerm {
//   roleId: number
//   permissions: string[]
// }
interface Role {
  roleId: number
  roleName: string
  status: string
}

// 从角色管理页获取的角色列表
const roles = ref<Role[]>([])
// 当前选中的角色
const selectedRole = ref<Role>()
// 权限树数据
const permissionTree = ref<Permission[]>([])
// 选中的权限keys
const checkedKeys = ref<string[]>([])

// 模拟权限数据（实际应从接口获取）
const mockPermissions: Permission[] = [
  {
    id: 'sys',
    label: '系统管理',
    isMenu: true,
    children: [
      {
        id: 'user:manage',
        label: '用户管理',
        isMenu: true,
        children: [
          { id: 'user:create', label: '新增用户' },
          { id: 'user:edit', label: '编辑用户' },
          { id: 'user:delete', label: '删除用户' },
        ],
      },
      {
        id: 'role:manage',
        label: '角色管理',
        isMenu: true,
        children: [
          { id: 'role:create', label: '新增角色' },
          { id: 'role:edit', label: '编辑角色' },
          { id: 'role:delete', label: '删除角色' },
        ],
      },
    ],
  },
  {
    id: 'order',
    label: '订单管理',
    isMenu: true,
    children: [
      { id: 'order:view', label: '查看订单' },
      { id: 'order:export', label: '导出订单' },
    ],
  },
]

// 加载权限数据
async function loadPermissions() {
  // 实际应调用接口获取
  permissionTree.value = mockPermissions
}

// 加载角色数据
async function loadRoles() {
  // 实际应调用接口获取
  roles.value = [
    { roleId: 1, roleName: '超级管理员', status: '启用' },
    { roleId: 2, roleName: '普通管理员', status: '启用' },
  ]
}

// 角色选择变化处理
async function handleRoleChange(role: Role) {
  if (!role) {
    checkedKeys.value = []
    return
  }

  // 模拟获取角色权限（实际应调用接口）
  checkedKeys.value = role.roleId === 1
    ? ['sys', 'user:manage', 'user:create', 'user:edit', 'user:delete', 'role:manage']
    : ['order:view']
}

// 提交权限分配
async function submitPerms() {
  if (!selectedRole.value) {
    ElMessage.warning('请先选择角色')
    return
  }

  // const payload: RolePerm = {
  //   roleId: selectedRole.value.roleId,
  //   permissions: checkedKeys.value,
  // }
  // console.warn('提交权限分配:', payload)
  ElMessage.success('权限分配成功')
}

// 初始化加载
onMounted(() => {
  loadRoles()
  loadPermissions()
})
</script>

<template>
  <div class="perm-container">
    <FaPageMain>
      <!-- 顶部操作栏 -->
      <div class="operate-bar">
        <el-select
          v-model="selectedRole"
          placeholder="选择角色"
          filterable
          @change="handleRoleChange"
        >
          <el-option
            v-for="role in roles"
            :key="role.roleId"
            :label="role.roleName"
            :value="role"
          />
        </el-select>

        <el-button
          type="primary"
          :disabled="!selectedRole"
          @click="submitPerms"
        >
          保存权限分配
        </el-button>
      </div>

      <!-- 权限树形结构 -->
      <div class="perm-tree">
        <el-tree
          v-model:checked-keys="checkedKeys"
          :data="permissionTree"
          show-checkbox
          node-key="id"
          :props="{
            children: 'children',
            label: 'label',
          }"
          :check-strictly="false"
          :default-expand-all="true"
          :expand-on-click-node="false"
        >
          <template #default="{ node, data }">
            <span class="perm-node">
              <el-icon v-if="data.isMenu">
                <FolderOpened />
              </el-icon>
              <el-icon v-else>
                <Document />
              </el-icon>
              <span class="ml-2">{{ node.label }}</span>
            </span>
          </template>
        </el-tree>
      </div>
    </FaPageMain>
  </div>
</template>

<style scoped>
.perm-container {
  height: calc(100vh - 120px);
}

.operate-bar {
  display: flex;
  gap: 20px;
  margin-bottom: 20px;
}

.perm-tree {
  height: calc(100vh - 200px);
  padding: 15px;
  overflow: auto;
  border: 1px solid #ebeef5;
  border-radius: 4px;
}

.perm-node {
  display: flex;
  align-items: center;
  font-size: 14px;

  :deep(.el-icon) {
    color: var(--el-color-primary);
  }
}
</style>
